import { extend, RequestOptionsInit, RequestMethod } from 'umi-request';
import { ElMessage } from 'element-plus';
import formatGatewayUrl from './formatGatewayUrl';
import requestAbort from './requestAbort';

interface IOpt extends RequestOptionsInit {
    // 是否走网关, 默认true
    encrypted?: boolean;
}

interface IRequestMethod extends RequestMethod {
    (url: string, options: IOpt): Promise<any>;
}

const request: IRequestMethod = extend({
    timeout: 10000,
    credentials: 'include',
    method: 'GET',
    errorHandler: (error) => {
      if(error?.['request']?.['options']?.['signal']) {
          console.warn('请求已被取消 signal--->', error?.['request']?.['options']?.['signal'])
          return Promise.resolve()
      }
      return error
    }
});

request.interceptors.request.use((pathname, options: IOpt) => {
    if (options.abort) {
        requestAbort.addPending(options)
    }
    const { data = {}, encrypted = true, ...rest } = options;
    let href = pathname;
    if (encrypted) {
        href = formatGatewayUrl(pathname, options);
    }
    return {
        url: href,
        options: { interceptors: true, ...rest, data },
    };
});

request.interceptors.response.use(async (response, options) => {
    const { responseType = 'json', customCode = false } = options;
    if (options.abort) {
        requestAbort.removePending(options);
    }
    if (!customCode) {
        if (responseType === 'json') {
            const data = await response.clone().json();
            if (data.httpCode === 401) {
                sessionStorage.clear();
                location.href = data.data;
                throw data;
            } else if (data.httpCode !== 200) {
                ElMessage.error(data.msg);
            }
        } else if (responseType === 'text') {
            await response.clone().text();
        }
    }
    return response;
});

export default request;